import React, { Component } from 'react';
import {
	StyleSheet, Text, View, Image, TouchableOpacity, Modal,
	ScrollView, PixelRatio, KeyboardAvoidingView, Platform, Keyboard
} from "react-native";
import { GLOBAL } from '../../config/global';
import { style } from '../../theme/style';
import { API, API_GENERATE } from '../../config/api';
import { SelectComponent } from '../order/create/_components/SelectComponent.js';
import { Common } from '../../component/common/Common.js'
import { UpDown } from '../order/create/_components/UpDown';
import ToastUtil from '../../utils/toast';
import { PageStatusIndex } from '../../component/page-status/PageStatusIndex';
import { AddressComponent } from '../order/create/_components/AddressComponent.js';
import HTTP from '../../utils/http';
import Dictionary from '../../utils/dictionary';
import ProductSelect from './modals/ProductSelect';
import { CURRENCY } from '../../utils/helper';
const scale = GLOBAL.SCALE;

let sendData = {};

// tCode        
// 长约->L  	
// 现货->S 代理->A   
// 背靠背->C         
// 远期->F 
// 长约执行->E

export class ProductFormPage extends Component {
	static navigationOptions = ({ navigation }) => {
		const params = navigation.state.params || {};
		const { addressCodeParam } = params;
		if (addressCodeParam) {
			addressObj = addressCodeParam;
			if (!addressObj.name) {
				addressObj.name = addressObj.poiInfo;
			}
		}
		return {
			header: null
		}
	};

	requesting;

	constructor(props) {
		super(props);
		this.state = {
			goodsModal: false,// 商品数据
			goodsValue: '请选择',
			goodsListVal: [],

			reasectPriceData: [],  // 暂定价（公式）
			reasectPriceOnoff: true,  // 是否有价格公式  true 有  false 无
			reasectPriceModal: false,
			reasectPriceValue: '请选择',
			reasectPriceIndex: -1,

			settlementPriceModal: false,  // 结算价  控制
			settlementPriceData: [],
			settlementPriceIndex: -1,
			settlementPriceValue: '请选择',

			quantityAppointModal: false,  // 品质约定
			quantityAppointData: [],
			quantityAppointIndex: -1,
			quantityAppointValue: '请选择',

			wIndex: 0,  // 暂定价下来的  tab切换

			status: 'data',   // 状态 

			oldGoodsData: false,   // 获取商品后显示其它信息

			editable: true, // 是否能够编辑 true-能编辑  false-不能编辑
			executeEditable: true,
			priceEditable: true,			// 暂定价是否可以编辑
			fixedPriceEditable: true, // 一口价是否可以编辑
		}

		// 展示数据
		this.showData = {
			planMonthLimitQuantity: 0, // 本月剩余可售/可采量
			planQuantity: 0, // 采购/销售 本月计划量
			onhandQuantity: 0, // 库存量
			longOrderPlan: 0, // 执行模式-商品总量
			longOrderLimit: 0, // 执行模式-商品剩余量
			stockQuantity: 0, // 分公司敞口库存
			stockQuantityMax: 0, // 敞口计划量，  敞口上限
			suggestedPrice: 0, // 当日现货价
			udPrice: '',
			purchaseUdPrice: '',
			saleUdPrice: '',
			huoIndex: 0,  // 升贴水
			purchaseUdIndex: 0, // 背靠背-采购升贴水
			saleUdIndex: 0, // 背靠背-采购升贴水
		}
		//1省区 2片区
		this.addressType = 1;
		this.goodsPriceData = {};

		this._save = this._save.bind(this);
	}

	async componentWillMount() {
		this.initPage();
		await this._dataDictionary();  // 数据字典

		if (this.editData) {
			this._editInit();  // 初始化
		}
	}

	componentWillUnmount() {
		this.editData = null
	}

	// 页面初始化
	initPage = () => {
		let {
			tCode, orderType, orderId, periodType, priceType, deliveryType, companyId, companyName, editData, isZXY,
			companyIdBuy, companyNameBuy, agencyCompanyId, agencyCompanyName, oppoDeliveryType, longOrderId, currency, goodsStateList, orderPlanNotCheckFlag
		} = this.props.navigation.state.params;
		sendData = { orderType, orderId, periodType, priceType, companyId, companyName, deliveryType, longOrderId };
		this.tCode = tCode;
		this.isZXY = isZXY;
		this.deliveryType = deliveryType;
		this.orderType = orderType;
		this.editData = editData || null; // 编辑
		this.agencyCompanyId = agencyCompanyId || ''; // 代理需要用到的卖家id
		this.agencyCompanyName = agencyCompanyName || '';
		this.goodsState = editData ? editData.goodsState || '' : ''; // 编辑商品的类型， 如固体、液体
		this.goodsStateList = goodsStateList || [] // 除了当前商品的其他类型
		this.orderPlanNotCheckFlag = orderPlanNotCheckFlag == 1; // 是否是中新油企业
		if (this.goodsState && this.goodsStateList && this.goodsStateList.length > 0) {
			this.goodsStateList.splice(this.goodsStateList.indexOf(this.goodsState), 1)
		}
		// 判断币种，默认为'元'
		if (currency) {
			this.unit = CURRENCY.getUnit(currency).text;
			this.unitSymbol = CURRENCY.getUnit(currency).label;
		} else {
			this.unit = '元';
			this.unitSymbol = '￥';
		}
		// 背靠背
		if (tCode === 'C') {
			sendData.companyIdBuy = companyIdBuy;
			sendData.companyNameBuy = companyNameBuy;
			this.oppoDeliveryType = oppoDeliveryType;
		}
		// 长约执行 泉化
		if (this.tCode === 'E') {
			this.pushIndex = -1;
		}
	}

	_editInit = async (data) => {
		this.setState({
			status: 'loading'
		})
		let { orderId, itemId, goodsName, goodsId, quantity, priceType, purchasePrice, salePrice, price,
			udPrice, priceFormulaDesc, tempPriceFormulaId, purchaseUdPrice, saleUdPrice, qualityStd, qualityRemark,
			priceFormulaId, remark, priceFormlaId, assistQuantity, tmpPriceModel, longItemId,
		} = data ? data : this.editData;
		let { settlementPriceData, quantityAppointData } = this.state;
		let indexObj = {};
		// 品质约定
		if (quantityAppointData && quantityAppointData.length > 0) {
			quantityAppointData.forEach((item, index) => {
				if (item.dictKey == qualityStd) {
					indexObj.quantityAppointIndex = index;
					sendData.qualityStd = qualityStd
				}
			})
		}

		// 避免数据回填或切换商品的时候取到longorderID
		if (!data && this.editData && this.editData.orderId) {
			sendData.orderId = orderId;
		}
		if (this.tCode == 'E') {
			sendData.itemId = sendData.itemId ? sendData.itemId : itemId;
		} else {
			sendData.itemId = itemId;
		}
		sendData.goodsId = goodsId;
		sendData.goodsName = goodsName;
		sendData.longItemId = longItemId || '';
		//总量-初始化
		sendData.quantity = quantity ? quantity.toString() : '';
		// 长约执行选择商品后清空数量
		if (data) {
			sendData.quantity = ''
		}
		//价格类型 - 初始化
		sendData.priceType = priceType;
		sendData.tmpPriceModel = tmpPriceModel || '';
		// 品质约定说明
		sendData.qualityRemark = qualityRemark ? qualityRemark : '';
		if (this.tCode === 'C') {
			// 采购价
			sendData.purchasePrice = purchasePrice ? purchasePrice.toString() : '';
			// 销售价
			sendData.salePrice = salePrice ? salePrice.toString() : '';
			// 采购升贴水
			if (purchaseUdPrice) this.showData.purchaseUdIndex = purchaseUdPrice > 0 ? 0 : 1;
			this.showData.purchaseUdPrice = purchaseUdPrice ? Math.abs(purchaseUdPrice).toString() : '';
			// 销售升贴水
			if (saleUdPrice) this.showData.saleUdIndex = saleUdPrice > 0 ? 0 : 1;
			this.showData.saleUdPrice = saleUdPrice ? Math.abs(saleUdPrice).toString() : '';
		} else {
			sendData.price = price ? price.toString() : '';
		}

		if (this.tCode === 'F') {
			// 远期采购说明
			sendData.remark = remark;
		} else {
			this._getPriceData(tempPriceFormulaId || '');
		}
		// 暂定价 (背靠背无暂定价)
		if (this.tCode != 'C' && priceType == 2) {
			//升贴水- 正负号
			if (udPrice) this.showData.huoIndex = udPrice > 0 ? 0 : 1;
			//升贴水 - 数值
			this.showData.udPrice = udPrice ? Math.abs(udPrice).toString() : '0';
		}

		//结算价格公式 - 描述
		sendData.priceFormulaDesc = priceFormulaDesc;
		//结算价公式 -id
		sendData.priceFormulaId = priceFormulaId;

		//结算价-公式 - 初始化
		settlementPriceData = await this._settlementPriceData();

		this._planInit();  // 计划量
		this.getInventoryInfo(); // 获取库存信息
		this.getLatestPrice(); // 获取当日现货价格
		this.setState({
			wIndex: (this.tCode == 'E' || price || purchasePrice || salePrice || !tempPriceFormulaId) ? '0' : '1',
			settlementPriceValue: priceFormulaDesc ? priceFormulaDesc : '请选择',
			goodsValue: goodsName,  // 商品名
			// 品质约定
			quantityAppointValue: quantityAppointData[indexObj.quantityAppointIndex] ? quantityAppointData[indexObj.quantityAppointIndex].dictName : '',
			quantityAppointIndex: indexObj.quantityAppointIndex
		})
		if (this.tCode === 'E') {
			// 长约执行获取当前商品数量
			this.executeProductInfo();
			// 长约执行需要判断部分表单是否禁用
			this.formDisabled(data || this.editData);
			this.setState({
				oldGoodsData: data ? data : this.editData,
			})
		}
		// 结算价 (tCode === 'S' || 'A' || 'F')
		if ((this.tCode === 'S' || 'A' || 'F') && settlementPriceData && settlementPriceData.length > 0) {
			settlementPriceData && settlementPriceData.forEach((item, index) => {
				if (item.formulaId == priceFormulaId) {
					this.setState({
						settlementPriceIndex: index
					})
				}
			})
		}
		this.setState({
			status: 'data'
		})
	}

	// 长约执行需要判断部分表单是否禁用
	formDisabled = (executeInfo) => {
		let editable = false;
		let priceEditable = true;
		let executeEditable = true;
		let fixedPriceEditable = true;
		// 如果价格填写了，则不可修改	
		if (executeInfo.price) priceEditable = false
		// 如果结算价、结算公式、升贴水都填写了，则不可编辑，否则这三项可以编辑
		if (executeInfo.udPrice && executeInfo.tempPriceFormulaId && executeInfo.priceFormulaId) {
			executeEditable = false;
		} else {
			priceEditable = true;
		}
		// 没填价格 或者 价格类型是一口价（变），则允许修改
		fixedPriceEditable = (!executeInfo.price) || (executeInfo.tmpPriceModel && executeInfo.tmpPriceModel == 3);
		this.setState({
			priceEditable, executeEditable, editable, fixedPriceEditable
		})
	}

	//数据字典-初始化
	async _dataDictionary() {
		this.setState({
			status: 'loading'
		})
		let quantityAppointData = await Dictionary.get('GOODS_QUALITY_STANDARD');
		this.setState({
			quantityAppointData: quantityAppointData || [],
			status: 'data'
		});
		return new Promise((resolve, reject) => {
			resolve(true);
		})
	}

	// 初始化-计划量
	async	_planInit() {
		let { isUnite } = this.props.navigation.state.params;
		let responseData = await HTTP.POST(API_GENERATE(API.ORDER_GOODS_PLAN), {
			goodsId: sendData.goodsId,
			planType: sendData.orderType,
			orderId: sendData.orderId,
			isUnite,
		})
		if (responseData) {
			let { planQuantity, planMonthLimitQuantity, onhandQuantity } = responseData;
			this.showData.planQuantity = planQuantity;
			this.showData.planMonthLimitQuantity = planMonthLimitQuantity;
			this.showData.onhandQuantity = onhandQuantity;
			this.setState({
				ls: true
			}, () => {
				this.checkPlanQuantity()
			})
		}
	}

	// 计划量控制
	checkPlanQuantity = () => {
		let { isUnite } = this.props.navigation.state.params;
		// 长约执行采购 中新油的企业不需要控
		if (this.tCode == 'E' && this.orderPlanNotCheckFlag) return
		if (this.tCode == 'S' || this.tCode == 'E') {
			// 下面情况需要计划管控 isUnite 0-自营  1-统销
			// isUnite == 0  orderType == 'P'
			// isUnite == 0  orderType == 'S'
			// isUnite == 1  orderType == 'S'
			if ((sendData.orderType == 'P' && isUnite == '0') || (sendData.orderType == 'S' && (isUnite == '0' || isUnite == '1'))) {
				if (!this.showData.planMonthLimitQuantity && this.showData.planMonthLimitQuantity != 0) {
					ToastUtil.showWarning('暂无提报计划量，请提报后提交', 1500);
					return true
				}
				if ((this.showData.planMonthLimitQuantity || this.showData.planMonthLimitQuantity == 0) && sendData.quantity && (parseFloat(sendData.quantity) > parseFloat(this.showData.planMonthLimitQuantity))) {
					ToastUtil.showWarning(`${sendData.orderType == 'P' ? '采购量' : '销售量'}大于计划量，请调整后提交`, 1500);
					return true
				}
			}
		}
	}

	// 初始化-长约框架-商品总量/商品剩余
	async executeProductInfo() {
		let responseData = await HTTP.POST(API_GENERATE(API.ORDER_EXECUTE_PLAN), { goodsId: sendData.goodsId, longOrderId: sendData.longOrderId, orderId: sendData.orderId, longItemId: sendData.longItemId })
		if (responseData) {
			let { longOrderPlan, longOrderLimit, longOrderMax } = responseData
			this.showData.longOrderPlan = longOrderPlan;
			this.showData.longOrderLimit = longOrderLimit;
			this.showData.longOrderMax = longOrderMax;
			this.setState({
				ls: true
			})
		}
	}

	// 初始化-敞口库存
	async getInventoryInfo() {
		let params = {
			goodsId: sendData.goodsId,
		}
		let res = await HTTP.POST(API_GENERATE(API.GET_NEW_GOODS_QUANTITY), params);
		if (res) {
			let { stockQuantity, stockQuantityMax } = res;
			this.showData.stockQuantity = stockQuantity; // 分公司敞口库存
			this.showData.stockQuantityMax = stockQuantityMax; // 敞口上限
			this.setState({
				ls: true
			})
		}
	}

	// 获取当日现货价
	async getLatestPrice() {
		let responseData = await HTTP.POST(API_GENERATE(API.GET_LATEST_PRICE), { goodsId: sendData.goodsId });
		if (responseData) {
			let { suggestedPrice } = responseData;
			this.showData.suggestedPrice = suggestedPrice;
			this.setState({
				ls: true
			})
		}
	}

	//暂定价（公式）
	async _getPriceData(id) {
		if (sendData.goodsId) {
			this.setState({
				status: 'loading'
			})
			let responseData = await HTTP.POST(API_GENERATE(API.GET_PRICE), { goodsId: sendData.goodsId, orderType: sendData.orderType });
			let indexObj = {};
			responseData.map((item, index) => {
				item.dictName = item.formulaName;
				if (id && id == item.formulaId) {
					indexObj.priceIndex = index;
					sendData.tempPriceFormulaId = id
				}
			});
			this.setState({
				reasectPriceData: responseData,
				reasectPriceOnoff: responseData.length > 0 ? true : false,
				reasectPriceValue: responseData[indexObj.priceIndex] ? responseData[indexObj.priceIndex].formulaName : '请选择',
				reasectPriceIndex: indexObj.priceIndex,
				status: 'data'
			})
		}
	}

	//结算价公式 - 数据 
	async	_settlementPriceData() {
		if (sendData.goodsId) {
			this.setState({
				status: 'loading'
			})
			let responseData = await HTTP.POST(API_GENERATE(API.GET_PRICE), {
				goodsId: sendData.goodsId,
				orderType: sendData.orderType
			});
			if (!responseData) return resolve()
			responseData.map((item, index) => {
				item.dictName = item.formulaName;
			});
			this.setState({
				status: 'data',
				settlementPriceData: responseData,
			})
			return new Promise((resolve, reject) => {
				resolve(responseData);
			})
		}
	}



	// 获取商品参数
	_getGoodsParams = () => {
		let params = {
			priceType: sendData.priceType,
			goodsState: this.goodsState,
			goodsStateList: this.goodsStateList,
			orderType: sendData.orderType,
			bizMode: 0 // 敞口-0  闭口-1
		};
		if (this.tCode == 'C') {
			// 背靠背模式需要选择客户和供应商的商品
			params.companyIdList = [sendData.companyId, sendData.companyIdBuy];
			params.bizMode = 1;
			params.orderType = '';
		} else if (this.tCode == 'A') {
			params.companyIdList = [this.agencyCompanyId, sendData.companyId]
		} else {
			params.companyId = sendData.companyId
		}
		return params;
	}

	// 选择商品名称
	selectProductName = () => {
		if (this.tCode === 'E') {
			this._gotoGoodsList({})
		} else {
			let { goodsModal } = this.state;
			this._selecGoods({ goodsModal })
		}
	}

	//打开模态框
	_selecGoods = (obj, index) => {
		var onTe = true;
		for (key in obj) {
			obj[key] = true;
			if (key == 'settlementPriceModal' || key == 'reasectPriceModal') {
				onTe = this.state.executeEditable;
				if (!sendData.goodsId) {
					onTe = false;
					ToastUtil.showWarning('请先选择商品');
				}
			} else {
				onTe = this.state.editable
			}
		}
		if (onTe) {
			this.setState(obj);
		}
	}

	//选择暂定价（公式）
	_reasectPriceCallBack = (index) => {
		this.setState({
			reasectPriceModal: false,
			reasectPriceValue: this.state.reasectPriceData[index].formulaName,
			reasectPriceIndex: index
		}, () => {
			sendData.tempPriceFormulaId = this.state.reasectPriceData[index].formulaId;
		})
	}

	//选择结算价（公式）
	_settlementPriceCallBack = (index) => {
		this.setState({
			settlementPriceModal: false,
			settlementPriceValue: this.state.settlementPriceData[index].formulaName,
			settlementPriceIndex: index
		}, () => {
			sendData.priceFormulaId = this.state.settlementPriceData[index].formulaId;
		})
	}

	// 品质约定
	_quantityAppointCallBack = (index) => {
		sendData.qualityStd = this.state.quantityAppointData[index].dictKey;
		this.setState({
			quantityAppointModal: false,
			quantityAppointValue: this.state.quantityAppointData[index].dictName,
			quantityAppointIndex: index
		})
	}

	//价格 - 一口价 - 输入
	_getPrice = (str) => {
		if (this.tCode === 'C') {
			sendData.purchasePrice = str;
		} else {
			sendData.price = str;
		}
	}

	//价格 - 一口价 - 输入 - 销售
	_getPriceSell(str) {
		sendData.salePrice = str;
	}

	//品质说明 - 输入
	_quantityAppoint(str) {
		sendData.qualityRemark = str;
	}

	//总量 -  输入
	_allQuantity(str) {
		sendData.quantity = str;
	}

	//暂定价 - 输入
	_tempPrice = (str) => {
		if (this.tCode === 'C') {
			sendData.purchasePrice = parseFloat(str);
		} else {
			sendData.price = parseFloat(str);
		}
	}

	//暂定价 - 输入 -销售
	_tempPriceSell(str) {
		sendData.salePrice = parseFloat(str);
	}

	//远期采购说明 -  输入
	_remark = (str) => {
		sendData.remark = str;
	}

	//顶部关闭按钮
	_headCloes = () => {
		this.props.navigation.goBack();
	}
	// 升贴水 回调函数
	_upDownFn = (options) => {
		if (this.tCode === 'C') {
			this.showData.purchaseUdPrice = options.value;
			this.showData.purchaseUdIndex = options.selectIndex;
		} else if (this.state.executeEditable) {
			this.showData.udPrice = options.value;
			this.showData.huoIndex = options.selectIndex;
		}
		this.setState({
			ls: true
		})
	}
	// 升贴水(客户) 回调函数
	_upDownFnSell = (options) => {
		this.showData.saleUdPrice = options.value;
		this.showData.saleUdIndex = options.selectIndex;
		this.setState({
			ls: true
		})
	}
	//俩组数组去重
	_createArr = (oldArr, newArr) => {
		let contArr = [];
		if (oldArr && oldArr.length > 0) {
			oldArr.forEach(item => {
				newArr.forEach((items, index) => {
					if (item.addrId === items.addrId) {
						newArr.splice(index, 1);
					}
				})
			});
			contArr = oldArr.concat(newArr);
		} else {
			contArr = newArr;
		}
		return contArr;
	}

	verifyReturn = () => {
		if (!sendData.goodsId) {
			ToastUtil.showWarning('请选择商品');
			return
		}

		if (!sendData.quantity) {
			ToastUtil.showWarning('请输入数量');
			return
		}
		if (sendData.quantity && sendData.quantity <= 0) {
			ToastUtil.showWarning('数量必须大于0');
			return
		}
		// 计划量管控
		if (this.checkPlanQuantity()) return;
		if (this.tCode == 'C') {
			// 背靠背模式验证
			if (this.state.wIndex == '0' && !sendData.purchasePrice) {
				ToastUtil.showWarning('请输入采购单价');
				return
			} else if (this.state.wIndex == '0' && !sendData.salePrice) {
				ToastUtil.showWarning('请输入销售单价');
				return
			} else if (parseFloat(sendData.purchasePrice) > parseFloat(sendData.salePrice)) {
				ToastUtil.showWarning('销售合同单价不能小于采购合同单价');
				return
			} else if (sendData.priceType == '2' && this.state.wIndex == '1' && !sendData.tempPriceFormulaId) {
				ToastUtil.showWarning('请选择价格公式');
				return
			} else if (sendData.priceType == '2' && !sendData.priceFormulaId) {
				ToastUtil.showWarning('请选择结算价');
				return
			} else if (sendData.priceType == '2' && (!this.showData.purchaseUdPrice || !this.showData.saleUdPrice)) {
				ToastUtil.showWarning('请输入升贴水');
				return
			} else if (sendData.priceType == '2' && parseFloat(this.showData.saleUdPrice) < parseFloat(this.showData.purchaseUdPrice)) {
				ToastUtil.showWarning('销售升贴水须大于等于采购升贴水', 1500);
				return
			}
		}
		if (this.tCode != 'C') {
			// 其他模式验证
			if (this.state.wIndex == '0' && this.tCode != 'L' && !sendData.price) {
				ToastUtil.showWarning(sendData.priceType != '2' ? '请输入一口价' : '请输入暂定单价');
				return
			} else if (this.state.wIndex == '0' && sendData.price && sendData.price <= 0) {
				ToastUtil.showWarning(sendData.priceType != '2' ? '一口价必须大于0' : '暂定单价必须大于0');
				return
			} else if (this.tCode != 'L' && sendData.priceType == '2' && this.state.wIndex == '1' && !sendData.tempPriceFormulaId) {
				// 长约框架的结算价/结算公式/升贴水是非必填
				ToastUtil.showWarning('请选择价格公式');
				return
			} else if (this.tCode != 'L' && sendData.priceType == '2' && !sendData.priceFormulaId) {
				ToastUtil.showWarning('请选择结算价');
				return
			} else if (this.tCode != 'L' && sendData.priceType == '2' && !this.showData.udPrice) {
				ToastUtil.showWarning('请输入升贴水');
				return
			}
		}
		if (this.tCode == 'F' && !sendData.remark) {
			ToastUtil.showWarning(sendData.orderType == 'P' ? '请输入远期采购说明' : '请输入远期销售说明');
			return
		}
		if (!sendData.qualityStd) {
			ToastUtil.showWarning('请选择品质约定');
			return
		}
		if (sendData.qualityStd == '3' && !sendData.qualityRemark) {
			ToastUtil.showWarning('请输入品质说明');
			return
		}
		return true
	}

	//保存 
	async _save() {
		if (this.requesting) return;
		Keyboard.dismiss();
		if (!this.verifyReturn()) { return false; }

		let subData = {
			orderId: sendData.orderId,
			orderItemList: [{}]
		};
		// 判断升贴水是正还是负
		if (this.tCode == 'C') {
			sendData.purchaseUdPrice = this.showData.purchaseUdPrice ? (this.showData.purchaseUdIndex == 0 ? this.showData.purchaseUdPrice : -this.showData.purchaseUdPrice) : '';
			sendData.saleUdPrice = this.showData.saleUdPrice ? (this.showData.saleUdIndex == 0 ? this.showData.saleUdPrice : -this.showData.saleUdPrice) : '';
		}
		sendData.udPrice = this.showData.udPrice ? (this.showData.huoIndex == 0 ? this.showData.udPrice : -this.showData.udPrice) : 0;
		if (this.state.wIndex == '0') {
			sendData.tempPriceFormulaId = null
		} else {
			sendData.price = null;
			sendData.purchasePrice = null;
			sendData.salePrice = null;
		}
		subData.orderItemList[0] = sendData;
		this.setState({
			status: 'loading'
		})
		this.requesting = true;
		let saveData = await HTTP.POST(API_GENERATE(API.ORDER_SAVE_PRODUCT), subData);
		this.setState({
			status: 'data'
		})
		if (saveData) {
			ToastUtil.showSuccess('商品新增成功').then(() => {
				this.requesting = false;
				this.props.navigation.state.params.callBack('data');
				this.props.navigation.goBack();
			})
		} else {
			this.requesting = false;
		}
	}

	//查找字符串中的数字  并且返回数组
	_getNumberFn = (str) => {
		if (!str) return;
		var numberArr = [];
		var newStr = str.replace(/\d+/g, function () {
			numberArr.push(arguments[0]);
		});
		return numberArr.join('-');
	}

	/* ---选择产品--- */
	//选商品  确定按钮
	_confirmPress = (data) => {
		if (data.length > 0) {
			this.setState({
				goodsModal: false,
				goodsValue: data[0].goodsName,
			}, () => {
				let lastGoodsId = sendData.goodsId;
				sendData.goodsId = data[0].goodsId;
				sendData.goodsName = data[0].goodsName;
				if (this.tCode != 'F') this._getPriceData(sendData.tempPriceFormulaId || '');
				this._settlementPriceData()
				this._planInit();  // 计划量
				this.getInventoryInfo(); // 库存信息
				this.getLatestPrice(); // 当日现货价
				// 长约执行获取当前商品数量
				if (this.tCode == 'E') this.executeProductInfo();
				if (sendData.goodsId != lastGoodsId) {
					// 清空价格公式
					sendData.priceFormulaId = null;
					sendData.priceFormulaDesc = null;
					sendData.tempPriceFormulaId = null;
					this.setState({
						settlementPriceIndex: -1,
						settlementPriceValue: '请选择',
						reasectPriceIndex: -1,
						reasectPriceValue: '请选择',
					})
				}
			})
		} else {
			this.setState({
				goodsModal: false,
			})
		}
	}
	//商品取消按钮
	_cancelPress = () => {
		this.setState({
			goodsModal: false,
		})
	}

	//选取暂定价下面的 暂定价和 价格公式
	_dingjinFn = (str) => {
		if (!this.state.executeEditable) return;
		if (sendData.goodsId) {
			this.setState({ wIndex: str })
		} else {
			ToastUtil.showWarning('请先选择商品');
		}
	}

	// 关闭弹框
	_closeModal = (obj) => {
		for (key in obj) {
			obj[key] = false;
		}
		this.setState(obj);
	}

	//获取商品列表（仅执行需要）
	_gotoGoodsList = () => {
		this.props.navigation.navigate('ProductSelectPage', {
			pushIndex: this.pushIndex,
			orderId: sendData.longOrderId,
			type: 'EXECUTE',
			callBack: (data, index) => {
				if (data) {
					this.pushIndex = index;
					this._editInit(data);
				}
			}
		});
	}

	// 删除一条数据
	_removeAddress = (index, addressData) => {
		addressData.splice(index, 1);
		this.setState({
			ls: true
		})
	}

	// 预览价格曲线
	_viewCharts = () => {
		if (sendData.goodsId) {
			this.props.navigation.navigate('ProductPriceDetailPage', {
				data: {
					goodsId: sendData.goodsId,
					goodsName: sendData.goodsName
				}
			});
		} else {
			ToastUtil.showWarning('请先选择商品');
		}
	}

	// 渲染商品的数量
	_renderProductCount = () => {
		let isBuyer = sendData.orderType == 'P';
		let buyerOrSellerText = isBuyer ? '采购' : '销售';
		let planText = isBuyer ? '当月剩余可采计划量' : '当月剩余可售计划量';
		let { goodsValue } = this.state;
		let { onhandQuantity, longOrderPlan, longOrderLimit, planQuantity, planMonthLimitQuantity, stockQuantity, stockQuantityMax } = this.showData;
		if (this.tCode == 'L') {
			// 长约采购/销售框架
			return (
				<Text style={styles.info}>分公司敞口库存{stockQuantity || '--'}吨</Text>
			)
		} else if (this.tCode == 'E') {
			// 长约采购/销售执行
			return (
				<Text style={styles.info}>
					{buyerOrSellerText}{goodsValue} 商品总量{longOrderPlan || '--'}吨；商品剩余{longOrderLimit || '--'}吨；
					{/* 当月{buyerOrSellerText}计划{planQuantity || '--'}吨； */}
					{planText}{planMonthLimitQuantity || '--'}吨；
					分公司敞口库存{stockQuantity || '--'}吨；
					{isBuyer ? '敞口上限' + (stockQuantityMax || '--') + '吨；' : ''}
				</Text>
			)
		} else if (this.tCode == 'S' || this.tCode == 'F') {
			// 采购/销售现货 || 采购远期/销售成交
			return (
				<Text style={styles.info}>
					{/* 当月{buyerOrSellerText}计划{planQuantity || '--'}吨； */}
					{planText}{planMonthLimitQuantity || '--'}吨；
					分公司敞口库存{stockQuantity || '--'}吨；
					{isBuyer ? '敞口上限' + (stockQuantityMax || '--') + '吨；' : ''}
				</Text>
			)
		} else if (this.tCode == 'A') {
			// 代理销售
			return (
				<Text style={styles.info}>
					{/* 当月{buyerOrSellerText}计划{planQuantity || '--'}吨； */}
					{planText}{planMonthLimitQuantity || '--'}吨；
				</Text>
			)
		}
	}

	viewMore = () => {

	}

	render() {
		let {
			reasectPriceData, reasectPriceModal, reasectPriceValue, reasectPriceIndex, reasectPriceOnoff,
			goodsModal, goodsValue,
			goodsList, goodsListVal, wIndex, status,
			settlementPriceIndex, settlementPriceData, settlementPriceModal, settlementPriceValue,
			quantityAppointModal, quantityAppointData, quantityAppointIndex, quantityAppointValue,
			oldGoodsData, editable, executeEditable, priceEditable, fixedPriceEditable
		} = this.state;
		let { priceType } = sendData;
		let { onhandQuantity, longOrderPlan, longOrderLimit, suggestedPrice, huoIndex, purchaseUdIndex, saleUdIndex, udPrice, purchaseUdPrice, saleUdPrice } = this.showData;
		let ProductSend = [];
		if (sendData.goodsId) {
			ProductSend.push({ goodsId: sendData.goodsId, goodsName: sendData.goodsName })
		}
		return (
			<KeyboardAvoidingView style={styles.container} behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={20}>
				<ScrollView style={{ paddingLeft: 15 * scale, paddingRight: 15 * scale }} keyboardShouldPersistTaps={'handled'}>
					<Common type="headCloes" callBack={this._headCloes} />
					<Text style={styles.topH1}>商品信息</Text>
					<View style={styles.formBox}>
						{/* 计价类型 */}
						{priceType ? <SelectComponent name="计价类型" type="input" value={priceType != 2 ? '一口价' : '暂定价'} editable={false} /> : null}


						{/* 选择商品 */}
						<SelectComponent name="商品名称" value={goodsValue} callBack={() => { this.selectProductName() }} />
						{/* 长约执行，有oldGoodsData才显示下面的数据 */}
						{
							(this.tCode != 'E' || (this.tCode === 'E' && oldGoodsData)) ?
								(<View>
									{/* 总量 */}
									<SelectComponent keyboardType="numeric" name="数量" value={sendData.quantity} inputFn={this._allQuantity} onBlurFn={() => {
										if (sendData.goodsId && sendData.quantity && sendData.quantity.length > 0) {
											this.checkPlanQuantity()
										}
									}
									} type={'input'} rightText={'吨'} />

									{/* 商品数量 */}
									<View>
										{
											sendData.goodsId ? this._renderProductCount() : null
										}
									</View>

									{/* 查看曲线 */}
									<View style={{ width: '100%' }}>
										<View style={styles.tHead}>
											<Text style={styles.tHeadText}>当期市场价格</Text>
											<TouchableOpacity>
												<Text style={styles.tHeadRight} onPress={() => { this._viewCharts() }}>查看曲线></Text>
											</TouchableOpacity>
										</View>
									</View>

									{/* 根据不同计价方式显示 */}
									{
										// 计价方式-一口价显示内容
										priceType != '2' ?
											(this.tCode === 'C' ?
												// 背靠背模式
												<View>
													<SelectComponent keyboardType="numeric" editable={editable} icon={this.unitSymbol} rightText={this.unit + '/吨'} value={sendData.purchasePrice} name="合同单价(采购)" type='input' inputFn={this._getPrice} />
													<SelectComponent keyboardType="numeric" editable={editable} icon={this.unitSymbol} rightText={this.unit + '/吨'} value={sendData.salePrice} name="合同单价(销售)" type='input' inputFn={this._getPriceSell} />
													{sendData.goodsId ? (<Text style={styles.info}>当日现货价 {this.unitSymbol}{suggestedPrice || '--'}{this.unit}/吨</Text>) : null}
												</View>
												:
												// 其他模式
												<View>
													<SelectComponent keyboardType="numeric" editable={fixedPriceEditable} rightText={this.unit + '/吨'} icon={this.unitSymbol} value={sendData.price && sendData.price.toString()} name="一口价" type='input' inputFn={this._getPrice} />
													{sendData.goodsId ? (<Text style={styles.info}>当日现货价 {this.unitSymbol}{suggestedPrice || '--'}{this.unit}/吨</Text>) : null}
												</View>
											)
											:
											// 计价方式-暂定价显示内容
											(<View>
												<View>
													<View style={styles.selectBox}>
														<Text onPress={() => { this._dingjinFn(0) }} style={[styles.selectItem, wIndex == 0 ? styles.selectItemActive : null]}>暂定单价(金额) </Text>
														{
															(this.tCode != 'E' && sendData.periodType == 'L') ? (<Text onPress={() => { this._dingjinFn(1) }} style={[styles.selectItem, wIndex == 1 ? styles.selectItemActive : null]}>暂定单价(公式)</Text>) : null
														}
														{sendData.goodsId ? (<Text style={[styles.info, { fontSize: 12, marginTop: 0 * scale }]}>当日现货价 ¥{suggestedPrice || '--'}</Text>) : null}
													</View>
													{
														wIndex == 0 ?
															(
																this.tCode === 'C' ?
																	(
																		// 背靠背模式
																		<View>
																			<SelectComponent keyboardType="numeric" editable={editable} icon={'(采购)' + this.unitSymbol} rightText={this.unit + '/吨'} value={sendData.purchasePrice && sendData.purchasePrice.toString()} type='input' inputFn={this._tempPrice} />
																			<SelectComponent keyboardType="numeric" editable={editable} icon={'(销售)' + this.unitSymbol} rightText={this.unit + '/吨'} value={sendData.salePrice && sendData.salePrice.toString()} type='input' inputFn={this._tempPriceSell} />
																		</View>
																	)
																	:
																	// 其他模式
																	<SelectComponent keyboardType="numeric" editable={priceEditable} icon={this.unitSymbol} rightText={this.unit + '/吨'} value={sendData.price && sendData.price.toString()} type='input' inputFn={this._getPrice} />
															)
															: (reasectPriceOnoff ? (<TouchableOpacity onPress={() => { this._selecGoods({ reasectPriceModal }) }} style={[styles.priceGu, { justifyContent: 'space-between' }]}>
																<Text style={{ color: style.color.dark }}>{reasectPriceValue}</Text>
																<Image style={styles.arrowLeft} source={require('../../imgs/arrow-left.png')} />
															</TouchableOpacity>) : (<Text style={styles.noGs}>该商品暂无价格公式</Text>))
													}
													<SelectComponent keyboardType="numeric" callBack={() => { this._selecGoods({ settlementPriceModal }) }} name="结算价" value={settlementPriceValue} />
												</View>

												{
													this.tCode === 'C' ?
														// 背靠背模式有两个升贴水
														(<View>
															<View>
																<View style={styles.tHead}>
																	<Text style={styles.tHeadText}>升贴水<Text style={styles.textActive}>采购</Text></Text>
																</View>
																<View style={[styles.tBody, { marginTop: 12 * scale }]}>
																	<UpDown keyboardType="numeric" editable={executeEditable} unit={this.unit + '/吨'} value={purchaseUdPrice && purchaseUdPrice.toString()} selectIndex={purchaseUdIndex} callBack={this._upDownFn} />
																</View>
															</View>
															<View>
																<View style={styles.tHead}>
																	<Text style={styles.tHeadText}>升贴水<Text style={styles.textActive}>销售</Text></Text>
																</View>
																<View style={[styles.tBody, { marginTop: 12 * scale }]}>
																	<UpDown keyboardType="numeric" editable={executeEditable} unit={this.unit + '/吨'} value={saleUdPrice && saleUdPrice.toString()} selectIndex={saleUdIndex} callBack={this._upDownFnSell} />
																</View>
															</View>
														</View>)
														:
														// 其他模式的升贴水
														(<View>
															<View style={styles.tHead}>
																<Text style={styles.tHeadText}>升贴水</Text>
															</View>
															<View style={[styles.tBody, { marginTop: 12 * scale }]}>
																<UpDown keyboardType="numeric" editable={executeEditable} unit={this.unit + '/吨'} value={udPrice && udPrice.toString()} selectIndex={huoIndex} callBack={this._upDownFn} />
															</View>
														</View>)
												}
											</View>
											)
									}

									{/* 远期采购说明 */}
									{
										this.tCode === 'F' ?
											<SelectComponent name={sendData.orderType == 'P' ? '远期采购说明' : '远期销售说明'} editable={editable} type={'input'} value={sendData.remark ? sendData.remark + '' : ''} inputFn={this._remark} />
											: null
									}

									{/* 品质约定 */}
									<SelectComponent callBack={() => { this._selecGoods({ quantityAppointModal }) }} name="品质约定" value={quantityAppointValue} />

									{/* 品质说明 品质约定选择'其他'时显示 */}
									{
										sendData.qualityStd == '3' ?
											<SelectComponent inputFn={this._quantityAppoint} editable={editable} type="input" name="品质说明" value={sendData.qualityRemark} />
											:
											null
									}
								</View>)
								: null
						}
					</View>

					{/* 保存按钮 */}
					<View style={{ width: '100%', height: 60 * scale, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginBottom: 20 * scale }}>
						<TouchableOpacity activeOpacity={.6} onPress={() => { this._save() }} style={[styles.btnSave, styles.mtp9]}>
							<Text style={styles.btnSaveText}>保存</Text>
						</TouchableOpacity>
					</View>

				</ScrollView>

				{/* 选择暂定价公式 */}
				<Common type="modal" demoData={(
					<Common type="listRadio" selectIndex={reasectPriceIndex} title="选择暂定价公式" listData={reasectPriceData} selectCallBack={this._reasectPriceCallBack} />
				)} isVisible={reasectPriceModal} closeCallballFn={() => { this._closeModal({ reasectPriceModal }) }} />

				{/* 选择结算公式 */}
				<Common type="modal" demoData={(
					<Common type="listRadio" selectIndex={settlementPriceIndex} title="选择结算公式" listData={settlementPriceData} selectCallBack={this._settlementPriceCallBack} />
				)} isVisible={settlementPriceModal} closeCallballFn={() => { this._closeModal({ settlementPriceModal }) }} />

				{/* 选择品质约定 */}
				<Common type="modal" demoData={(
					<Common type="listRadio" selectIndex={quantityAppointIndex} title="选择品质约定" listData={quantityAppointData} selectCallBack={this._quantityAppointCallBack} />
				)} isVisible={quantityAppointModal} closeCallballFn={() => { this._closeModal({ quantityAppointModal }) }} />

				{/* 商品选择弹窗 */}
				{
					(sendData.companyId != '' && goodsModal) ? (<ProductSelect
						confirmPress={this._confirmPress}
						cancelPress={this._cancelPress}
						sendData={this._getGoodsParams()}
						mainCheckData={ProductSend}
						modalVisible={goodsModal} />) : null
				}

				{
					status != 'data' ? (<View style={styles.statusStyle}><PageStatusIndex status={status} /></View>) : null
				}
			</KeyboardAvoidingView >
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.white,
	},
	topH1: {
		marginTop: 18 * scale,
		fontSize: 20 * scale,
		height: 28 * scale,
		lineHeight: 28 * scale,
		color: style.color.black,
		marginBottom: 3 * scale
	},
	checkted: {
		backgroundColor: style.color.cerulean,
		color: style.color.white
	},
	mtp9: {
		marginTop: 9 * scale,
		marginBottom: 9 * scale
	},
	btnSave: {
		width: 345 * scale,
		height: 44 * scale,
		backgroundColor: style.color.themeColor,
		borderRadius: 22 * scale,
		position: 'absolute',
		bottom: 0
	},
	btnSaveText: {
		color: style.color.white,
		fontSize: 18 * scale,
		lineHeight: 44 * scale,
		textAlign: 'center',
	},
	info: {
		color: '#F66464',
		fontSize: 13 * scale,
		marginTop: 8 * scale
	},
	tHead: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		marginTop: 20 * scale
	},
	tHeadText: {
		fontSize: 12 * scale,
		color: style.color.darkGray,
	},
	tHeadRight: {
		fontSize: 12 * scale,
		color: style.color.cerulean
	},
	tBody: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
	},
	arrowLeft: {
		width: 6 * scale,
		height: 11 * scale
	},
	selectBox: {
		flexDirection: 'row',
		alignItems: 'center',
		height: 40 * scale,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.gray,
		marginTop: 10 * scale
	},
	selectItem: {
		fontSize: 12 * scale,
		color: style.color.darkGray,
		height: 40 * scale,
		lineHeight: 40 * scale,
		marginRight: 25 * scale
	},
	selectItemActive: {
		color: style.color.themeColor,
		borderBottomWidth: 2 * scale,
		borderStyle: 'solid',
		borderBottomColor: style.color.themeColor,
	},
	priceGu: {
		height: 45 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.gray,
	},
	noGs: { color: style.color.dark, marginTop: 10 * scale, color: '#F66464' },
	statusStyle: {
		flex: 1,
		position: 'absolute',
		height: '100%',
		width: '100%',
		top: 0,
		left: 0,
		flexDirection: 'column',
		justifyContent: 'center',
		alignItems: 'center'
	},
	formBox: {
		paddingBottom: 40 * scale
	},
})